package su.jet.irc.client.service;

import java.io.IOException;

import su.jet.common.irc.domain.Message;
import su.jet.common.irc.protocol.Session;
import su.jet.common.irc.protocol.request.GetHistoryRequest;
import su.jet.common.irc.protocol.request.Request;
import su.jet.common.irc.protocol.request.SendMessageRequest;

public class WriteService {
	private Request request;
	private MessageHandler messageHandler;
	private Session connectionWithServer;
		
	public WriteService(Session connectionWithServer, Session connectionWithReader,
			MessageHandler messageHandler) {
		this.messageHandler = messageHandler;
		this.connectionWithServer = connectionWithServer;
	}

	public void startMessageProcess() {
		runConsoleInput();
	}
	
	public void runConsoleInput() {
		while (true) {
			Message message = messageHandler.readFromConsole();
			boolean isPublicMessage = (message.getReceiver() == null) ? true : false;
			String textEntered = message.getText();
			if(textEntered.startsWith("**history")) {
				String [] historyArgs = textEntered.split(" ");
			try {
				request = new GetHistoryRequest(Integer.parseInt(historyArgs[1]), messageHandler.getSender());
			} catch (NumberFormatException e) {
				System.out.println("Incorrect history request. Format: **history days. Days is an integer constant.");
			} catch (ArrayIndexOutOfBoundsException e) {
				System.out.println("Incorrect history request. Format: **history days. Days is an integer constant.");
			}
			} else {
				request = new SendMessageRequest(message, isPublicMessage);;
			}

			try {
				if(request != null)
					connectionWithServer.sendRequest(request);
			} catch (IOException e) {
				System.out.println("Connection with server failed!");
			}
			
					
			if (message.getText().equals("end")) {
				break;
			}
		}
	}
}
